package cn.corffen.test.algorithm.leetcode.easy;

import java.util.Arrays;
import java.util.HashMap;

/**
 * 你从给定的数组中找到两个元素的和为指定值的两个索引
 */
public class TwoSum1 {

    public static void main(String[] args) {
        int[] numbers = new int[]{4, 2, 6, 5, 7};
        int[] result = twoSum(numbers, 9);
        if (result != null) {
            System.out.println(Arrays.toString(result));
        }
    }

    public static int[] twoSum(int[] nums, int target) {
        int n = nums.length;
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < n; i++) {
            if (map.containsKey(nums[i])) {
                return new int[]{i, map.get(nums[i])};
            } else {
                map.put(target - nums[i], i);
            }
        }
        return null;
    }

}
